import { PrismaClient, Prisma } from '@prisma/client'

interface QueryOptions {
  idNumber?: string
  username?: string
  userId?: number
  limit: number
  includeSettlements: boolean
}

const prisma = new PrismaClient()

const parseArgs = (): QueryOptions => {
  const options: QueryOptions = {
    limit: 50,
    includeSettlements: true
  }

  for (const arg of process.argv.slice(2)) {
    if (arg.startsWith('--id-number=')) {
      options.idNumber = arg.replace('--id-number=', '').trim()
    } else if (arg.startsWith('--username=')) {
      options.username = arg.replace('--username=', '').trim()
    } else if (arg.startsWith('--user-id=')) {
      const value = Number(arg.replace('--user-id=', '').trim())
      if (!Number.isNaN(value)) {
        options.userId = value
      }
    } else if (arg.startsWith('--limit=')) {
      const value = Number(arg.replace('--limit=', '').trim())
      if (!Number.isNaN(value) && value > 0) {
        options.limit = Math.min(value, 200)
      }
    } else if (arg === '--rewards-only') {
      options.includeSettlements = false
    } else {
      console.warn(`未知参数已忽略: ${arg}`)
    }
  }

  if (!options.idNumber && !options.username && !options.userId) {
    throw new Error('请至少通过 --id-number / --username / --user-id 指定一个查询条件')
  }

  return options
}

const formatDecimal = (value: Prisma.Decimal | number | null | undefined, fractionDigits = 4): string => {
  if (value === null || value === undefined) {
    return '0'
  }
  const num = typeof value === 'number' ? value : Number(value)
  return num.toFixed(fractionDigits)
}

const buildUserWhereClause = (options: QueryOptions): Prisma.UserWhereInput => {
  const filters: Prisma.UserWhereInput[] = []

  if (options.userId) {
    filters.push({ id: options.userId })
  }
  if (options.idNumber) {
    filters.push({ idNumber: options.idNumber })
  }
  if (options.username) {
    filters.push({ username: options.username })
  }

  if (filters.length === 1) {
    return filters[0]
  }

  return { OR: filters }
}

async function main(): Promise<void> {
  const options = parseArgs()
  console.log('查询条件:', options)

  const user = await prisma.user.findFirst({
    where: buildUserWhereClause(options),
    include: {
      stakingInfo: true
    }
  })

  if (!user) {
    console.error('未找到符合条件的用户')
    return
  }

  console.log('\n=== 用户基础信息 ===')
  console.log(`ID: ${user.id}`)
  console.log(`身份证/登录: ${user.idNumber}`)
  console.log(`姓名: ${user.name}`)
  console.log(`等级: ${user.tier}`)
  console.log(`注册时间: ${user.createdAt.toISOString()}`)

  if (user.stakingInfo) {
    const staking = user.stakingInfo
    console.log('\n--- 质押状态 ---')
    console.log(`质押本金(stakedAmount): ${formatDecimal(staking.stakedAmount)} NEAR`)
    console.log(`锁仓金额(lockedAmount): ${formatDecimal(staking.lockedAmount)} NEAR`)
    console.log(`日收益率(dailyRewardRate): ${formatDecimal(staking.dailyRewardRate, 6)}`)
    console.log(`当日总收益(currentDailyReward): ${formatDecimal(staking.currentDailyReward)} NEAR`)
    console.log(`已发放金额(dailyRewardDistributed): ${formatDecimal(staking.dailyRewardDistributed)} NEAR`)
    console.log(`已发放次数(dailyDistributionCount): ${staking.dailyDistributionCount}/${12}`)
    console.log(`下次发放时间(nextDistributionAt): ${staking.nextDistributionAt?.toISOString() ?? '未安排'}`)
    console.log(`最后收益计算(lastCalculationDate): ${staking.lastCalculationDate?.toISOString() ?? '未记录'}`)
    console.log(`累计收益(totalRewardsNear): ${formatDecimal(staking.totalRewardsNear)} NEAR`)
    console.log(`最近结算(lastSettlementDate): ${staking.lastSettlementDate?.toISOString() ?? '未记录'}`)
  } else {
    console.log('\n未找到该用户的质押记录。')
  }

  console.log('\n=== 最近发放记录 (staking_rewards) ===')
  const stakingRewards = await prisma.stakingReward.findMany({
    where: { userId: user.id },
    orderBy: { createdAt: 'desc' },
    take: options.limit
  })

  if (stakingRewards.length === 0) {
    console.log('暂无发放记录。')
  } else {
    stakingRewards.forEach((reward, index) => {
      console.log(
        `${index + 1}. ${reward.createdAt.toISOString()} | ` +
        `Amount: ${formatDecimal(reward.amount)} NEAR | ` +
        `Key: ${reward.distributionKey ?? 'N/A'}`
      )
    })
  }

  if (options.includeSettlements) {
    console.log('\n=== 最近结算记录 (staking_settlements) ===')
    const settlements = await prisma.stakingSettlement.findMany({
      where: { userId: user.id },
      orderBy: { settlementDate: 'desc' },
      take: options.limit
    })

    if (settlements.length === 0) {
      console.log('暂无结算记录。')
    } else {
      settlements.forEach((settlement, index) => {
        console.log(
          `${index + 1}. ${settlement.settlementDate.toISOString()} | ` +
          `Reward: ${formatDecimal(settlement.rewardNear)} NEAR | ` +
          `Rate: ${formatDecimal(settlement.dailyRewardRate, 6)} | ` +
          `Staked: ${formatDecimal(settlement.stakedAmount)} NEAR | ` +
          `Key: ${settlement.distributionKey ?? 'N/A'}`
        )
      })
    }
  }
}

main()
  .catch((error) => {
    console.error('查询过程发生错误:', error)
    process.exitCode = 1
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
